import React, { useEffect, useRef, useState } from 'react';
import { IndexData } from '@shared/types/market';

interface IndexCardProps {
  data: IndexData;
  onClick?: () => void;
}

const IndexCard: React.FC<IndexCardProps> = ({ data, onClick }) => {
  const [isUpdating, setIsUpdating] = useState(false);
  const prevDataRef = useRef<IndexData | null>(null);
  
  // 检测数据更新，触发闪烁动画
  useEffect(() => {
    if (prevDataRef.current && 
        prevDataRef.current.current !== data.current && 
        data._source === 'websocket') {
      setIsUpdating(true);
      const timer = setTimeout(() => setIsUpdating(false), 300);
      return () => clearTimeout(timer);
    }
    prevDataRef.current = data;
  }, [data]);
  
  // 检查是否有错误或数据不可用
  const hasError = 
    data.error || 
    data.current === undefined || 
    data.change === undefined || 
    data.change_pct === undefined ||
    data.high === undefined ||
    data.low === undefined ||
    (data.current === 0 && data.change === 0);
  
  const isPositive = !hasError && data.change >= 0;
  const changeColor = isPositive ? '#ef4444' : '#10b981'; // 红涨绿跌
  const arrow = isPositive ? '↑' : '↓';

  return (
    <div
      onClick={hasError ? undefined : onClick}
      style={{
        backgroundColor: 'white',
        borderRadius: '8px',
        border: `1px solid ${isUpdating ? '#3b82f6' : '#e5e7eb'}`,
        padding: '24px',
        transition: 'all 0.2s',
        cursor: hasError ? 'default' : 'pointer',
        opacity: hasError ? 0.6 : 1,
        boxShadow: isUpdating ? '0 0 12px rgba(59, 130, 246, 0.3)' : '0 1px 3px 0 rgba(0, 0, 0, 0.1)',
        position: 'relative',
      }}
      onMouseEnter={(e) => {
        if (!hasError && !isUpdating) {
          e.currentTarget.style.boxShadow = '0 10px 15px -3px rgba(0, 0, 0, 0.1)';
          e.currentTarget.style.borderColor = '#3b82f6';
        }
      }}
      onMouseLeave={(e) => {
        if (!hasError && !isUpdating) {
          e.currentTarget.style.boxShadow = '0 1px 3px 0 rgba(0, 0, 0, 0.1)';
          e.currentTarget.style.borderColor = '#e5e7eb';
        }
      }}
    >
      {/* WebSocket 更新指示器 */}
      {isUpdating && (
        <div
          style={{
            position: 'absolute',
            top: '8px',
            right: '8px',
            width: '6px',
            height: '6px',
            borderRadius: '50%',
            backgroundColor: '#3b82f6',
            animation: 'pulse 0.3s ease-in-out',
          }}
        />
      )}
      {/* 指数名称 */}
      <div style={{ 
        color: '#6b7280', 
        fontSize: '14px', 
        marginBottom: '8px', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between' 
      }}>
        <span>{data.name}</span>
        {hasError && <span style={{ fontSize: '12px', color: '#d97706' }}>⚠️ 暂无数据</span>}
      </div>

      {/* 当前点位 */}
      <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: '4px' }}>
        <span style={{ fontSize: '30px', fontWeight: 'bold', color: '#111827' }}>
          {hasError ? '--' : data.current.toLocaleString('zh-CN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </span>
      </div>

      {/* 涨跌信息 */}
      {!hasError && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
          <span
            style={{ fontSize: '18px', fontWeight: '600', color: changeColor }}
          >
            {arrow} {Math.abs(data.change).toFixed(2)}
          </span>
          <span
            style={{
              fontSize: '18px',
              fontWeight: '600',
              padding: '2px 8px',
              borderRadius: '4px',
              color: changeColor,
              backgroundColor: isPositive ? '#fee2e2' : '#d1fae5',
            }}
          >
            {isPositive ? '+' : ''}
            {data.change_pct.toFixed(2)}%
          </span>
        </div>
      )}
      {hasError && (
        <div style={{ fontSize: '14px', color: '#9ca3af', marginBottom: '16px' }}>
          数据暂时不可用
        </div>
      )}

      {/* 最高最低价和成交数据 */}
      {!hasError && (
        <div style={{ borderTop: '1px solid #e5e7eb', paddingTop: '12px', fontSize: '14px', color: '#6b7280' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>
              高: <span style={{ fontWeight: '500', color: '#111827' }}>{data.high.toFixed(2)}</span>
            </span>
            <span>
              低: <span style={{ fontWeight: '500', color: '#111827' }}>{data.low.toFixed(2)}</span>
            </span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px' }}>
            {data.volume !== undefined && (
              <span>
                成交量:{' '}
                <span style={{ fontWeight: '500', color: '#111827' }}>
                  {(data.volume / 100000000).toFixed(2)}亿手
                </span>
              </span>
            )}
            {data.amount !== undefined && (
              <span>
                成交额:{' '}
                <span style={{ fontWeight: '500', color: '#111827' }}>
                  {(data.amount / 100000000).toFixed(2)}亿
                </span>
              </span>
            )}
          </div>
        </div>
      )}

      {/* 更新时间 */}
      {data.timestamp && (
        <div style={{ fontSize: '12px', color: '#9ca3af', marginTop: '8px' }}>
          更新: {new Date(data.timestamp).toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          })}
        </div>
      )}
    </div>
  );
};

export default IndexCard;
